# app/middleware/logging.py
import time
import logging
from fastapi import Request

logger = logging.getLogger("app.middleware") # 初始化logger


async def logging_middleware(request: Request, call_next):
    """日志中间件 - 记录所有 HTTP 请求"""
    start_time = time.time()

    # 记录请求开始
    logger.info(f"Started {request.method} {request.url.path}")

    try:
        response = await call_next(request)

        # 计算处理时间
        process_time = time.time() - start_time

        # 记录请求完成
        logger.info(
            f"Completed {request.method} {request.url.path} "
            f"Status: {response.status_code} "
            f"Duration: {process_time:.3f}s"
        )

        # 添加响应头
        response.headers["X-Process-Time"] = str(process_time)
        return response

    except Exception as e:
        # 记录异常
        logger.error(
            f"Error in {request.method} {request.url.path}: {str(e)}",
            exc_info=True
        )
        raise
    